package com.keyboardr.gamerater.fragment.dialog;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;

import com.keyboardr.gamerater.R;
import com.keyboardr.gamerater.RaterActivity;
import com.keyboardr.gamerater.adapter.PlayerAdapter;
import com.keyboardr.gamerater.adapter.PlayerNameAdapter;
import com.keyboardr.gamerater.model.Player;

public class NewGameDialogFragment extends DialogFragment {
	protected static final String TAG = "NewGameDialogFragment";

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		final Dialog dialog = new Dialog(getActivity());
		dialog.setContentView(R.layout.new_game_dialog);
		dialog.setTitle(R.string.newGame);

		final AdapterView playerASpinner = (AdapterView) dialog
				.findViewById(R.id.playerASpinner);
		final AdapterView playerBSpinner = (AdapterView) dialog
				.findViewById(R.id.playerBSpinner);
		Adapter adapter;

		if (playerASpinner instanceof Spinner) {
			adapter = (playerASpinner instanceof Spinner) ? new PlayerNameAdapter<Player>(
					getActivity(), android.R.layout.simple_spinner_item,
					((RaterActivity) getActivity()).getSelectedGroup()
							.getPlayers()) : null;
			((ArrayAdapter<Player>) adapter)
					.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		} else {
			adapter = new PlayerAdapter((RaterActivity) getActivity());
			((AbsListView) playerASpinner)
					.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
			((AbsListView) playerBSpinner)
					.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

		}

		playerASpinner.setAdapter(adapter);
		playerBSpinner.setAdapter(adapter);

		playerASpinner.setSelection(0);
		playerBSpinner.setSelection(1);

		if (!(playerASpinner instanceof Spinner)) {
			((AbsListView) playerASpinner).setItemChecked(0, true);
			((AbsListView) playerBSpinner).setItemChecked(1, true);
		}

		final RadioGroup radios = (RadioGroup) dialog
				.findViewById(R.id.winnerGroup);
		radios.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup paramRadioGroup,
					int paramInt) {
				setButtonEnabled(dialog, playerASpinner, playerBSpinner, radios);
			}
		});

		if (playerASpinner instanceof Spinner) {
			playerASpinner
					.setOnItemSelectedListener(new OnItemSelectedListener() {

						@Override
						public void onItemSelected(AdapterView<?> arg0,
								View arg1, int arg2, long arg3) {
							setButtonEnabled(dialog, playerASpinner,
									playerBSpinner, radios);
						}

						@Override
						public void onNothingSelected(AdapterView<?> arg0) {
						}

					});
		} else {
			playerASpinner.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> paramAdapterView,
						View paramView, int paramInt, long paramLong) {
					playerBSpinner.setSelection(paramInt);
					((AbsListView) paramAdapterView).setItemChecked(paramInt,
							true);
					setButtonEnabled(dialog, playerASpinner, playerBSpinner,
							radios);
				}
			});
		}
		if (playerBSpinner instanceof Spinner) {
			playerBSpinner
					.setOnItemSelectedListener(new OnItemSelectedListener() {

						@Override
						public void onItemSelected(AdapterView<?> arg0,
								View arg1, int arg2, long arg3) {
							setButtonEnabled(dialog, playerASpinner,
									playerBSpinner, radios);
						}

						@Override
						public void onNothingSelected(AdapterView<?> arg0) {
						}

					});
		} else {
			playerBSpinner.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> paramAdapterView,
						View paramView, int paramInt, long paramLong) {
					playerBSpinner.setSelection(paramInt);
					setButtonEnabled(dialog, playerASpinner, playerBSpinner,
							radios);
				}
			});
		}

		final EditText handicapText = (EditText) dialog
				.findViewById(R.id.gameHandicapText);
		handicapText.addTextChangedListener(new TextWatcher() {

			@Override
			public void afterTextChanged(Editable arg0) {
				try {
					Double.parseDouble(arg0.toString());
				} catch (NumberFormatException e) {
					handicapText.setError(getString(R.string.invalid_handicap));
				}
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {

			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {

			}

		});

		final CheckBox handicapCheck = (CheckBox) dialog
				.findViewById(R.id.gameHandicapCheck);
		handicapCheck
				.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						handicapText.setVisibility(isChecked ? View.VISIBLE
								: View.GONE);
					}
				});

		Button okButton = (Button) dialog.findViewById(R.id.gameOkButton);
		okButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Player winner, loser;
				if (radios.getCheckedRadioButtonId() == R.id.playerBWinButton) {
					winner = getSelectedPlayer(playerBSpinner);
					loser = getSelectedPlayer(playerASpinner);
				} else {
					winner = getSelectedPlayer(playerASpinner);
					loser = getSelectedPlayer(playerBSpinner);
				}
				try {
					((RaterActivity) getActivity()).playGame(
							winner,
							loser,
							radios.getCheckedRadioButtonId() == R.id.drawButton,
							handicapCheck.isChecked() ? Double
									.parseDouble(handicapText.getText()
											.toString()) : 0);
					Log.d(TAG,
							"isDraw = "
									+ (radios.getCheckedRadioButtonId() == R.id.drawButton));
					dismiss();
				} catch (NumberFormatException e) {
					handicapText.setError(getString(R.string.invalid_handicap));
				}

			}

			private Player getSelectedPlayer(AdapterView view) {
				if (view instanceof Spinner) {
					return (Player) view.getSelectedItem();
				}
				int selected = ((AbsListView) view).getCheckedItemPosition();
				return (Player) view.getItemAtPosition(selected);
			}

		});
		Button cancelButton = (Button) dialog
				.findViewById(R.id.gameCancelButton);
		cancelButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
			}
		});
		return dialog;
	}

	@SuppressWarnings("rawtypes")
	public static void setButtonEnabled(Dialog dialog,
			AdapterView playerASpinner, AdapterView playerBSpinner,
			RadioGroup radios) {
		Button button = (Button) dialog.findViewById(R.id.gameOkButton);
		if (playerASpinner instanceof Spinner) {
			button.setEnabled(playerASpinner.getSelectedItemPosition() != playerBSpinner
					.getSelectedItemPosition()
					&& radios.getCheckedRadioButtonId() != -1);
		} else {
			button.setEnabled(((AbsListView) playerASpinner)
					.getCheckedItemPosition() != ((AbsListView) playerBSpinner)
					.getCheckedItemPosition()
					&& radios.getCheckedRadioButtonId() != -1);
		}
	}
}
